/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-11-24 22:18:20
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.risk.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ZipUtil;
import cn.zlg.common.springmvc.validate.constraints.NotNull;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.enums.RiskLevels;
import com.joysuch.wwyt.core.enums.Status;
import com.joysuch.wwyt.core.exception.ApiBusinessException;
import com.joysuch.wwyt.core.exception.ApiCoreException;
import com.joysuch.wwyt.dynamicdata.DynamicWriteData;
import com.joysuch.wwyt.risk.bean.*;
import com.joysuch.wwyt.risk.bean.RiskPointListBean.Search;
import com.joysuch.wwyt.risk.entity.RiskDistrict;
import com.joysuch.wwyt.risk.entity.RiskEvaluationRepo;
import com.joysuch.wwyt.risk.entity.RiskPoint;
import com.joysuch.wwyt.risk.entity.RiskPointType;
import com.joysuch.wwyt.risk.entity.vo.RiskPointDeleteCheckVO;
import com.joysuch.wwyt.risk.entity.vo.RiskPointVo;
import com.joysuch.wwyt.risk.enums.RiskPointStatus;
import com.joysuch.wwyt.risk.repository.RiskPointTypeDao;
import com.joysuch.wwyt.risk.service.RiskDistrictService;
import com.joysuch.wwyt.risk.service.RiskPointService;
import com.joysuch.wwyt.util.FileUtil;
import com.joysuch.wwyt.util.PrintExportUtil;
import com.joysuch.wwyt.util.QrCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/risk/point")
@Api(tags = "双预防-风险点管理")
@Slf4j
public class RiskPointController {

    private static final Logger logger = LoggerFactory.getLogger(RiskPointController.class);

    @Value("${wwyt.upload.unzip.tempdir}")
    private String zipTempDir;

    @Autowired
    private RiskPointService riskPointService;
    @Autowired
    private RiskDistrictService riskDistrctService;
    @Autowired
    private PrintExportUtil printExportUtil;
    @Autowired
    private RiskPointTypeDao riskPointTypeDao;

    @PostMapping("/pre-download-qr-code")
    @ApiOperation("风险点二维码下载前信息检查")
    public ResultBean preDownloadQrCode(@RequestBody PreDownloadQrCodeBean req) {
        List<RiskPoint> points = riskPointService.findByIdInIgnoreDeleteStatus(Sets.newHashSet(req.getIds()));
        List<RiskPoint> validPoints = points.stream()
                .filter(p -> !"1".equals(p.getDeleteFlag()) && (p.getShowState() == null || p.getShowState() != 44))
                .filter(p -> p.getSignInMethod() != null && p.getSignInMethod() == 3)
                .collect(Collectors.toList());

        PreDownloadQrCodeResBean res = new PreDownloadQrCodeResBean();
        res.setTotal(req.getIds().size());
        res.setValid(validPoints.size());
        return ResultBean.success(res);
    }

    @GetMapping("/download-qr-code")
    @ApiOperation("风险点二维码下载前信息检查")
    public ResponseEntity<Resource> downloadQrCode(String ids) throws FileNotFoundException {
        Set<Long> pointIds = Arrays.asList(ids.split(",")).stream()
                .map(Long::parseLong)
                .collect(Collectors.toSet());

        List<RiskPoint> points = riskPointService.findByIdInIgnoreDeleteStatus(pointIds);
        List<RiskPoint> validPoints = points.stream()
                .filter(p -> !"1".equals(p.getDeleteFlag()) && (p.getShowState() == null || p.getShowState() != 44))
                .filter(p -> p.getSignInMethod() != null && p.getSignInMethod() == 3)
                .collect(Collectors.toList());

        if (validPoints.size() == 0) {
            throw new IllegalArgumentException("未查询到二维码签到的风险点");
        }

        String folderName = DateUtil.format(new Date(), "yyyyMMddHHmmss") + new Random().nextInt(1000000);
        String tmpDir = zipTempDir + "/qrcode/" + folderName;
        File folder = new File(tmpDir);
        folder.mkdirs();

        for (RiskPoint p : validPoints) {
            String code = p.getId().toString();
            String text = p.getName() + "-" + p.getRiskDistrict().getName();
            String picPath = tmpDir + "/" + FileUtil.replaceFileNameSpecialCharacters(text) + ".png";
            try {
                QrCodeUtil.createQrFile(code, text, picPath);
            } catch (Exception e) {
                throw new RuntimeException("二维码生成失败！code: " + code + ", text: " + text + ", pic path: " + picPath , e);
            }
        }

        String zipPath = tmpDir + ".zip";
        ZipUtil.zip(tmpDir, zipPath);

        File zipFile = new File(zipPath);
        InputStreamResource resource = new InputStreamResource(new FileInputStream(zipFile));

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=qrcodes.zip");
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(zipFile.length())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }


    @PostMapping("addPointType")
    @ApiOperation("增加风险点类型")
    @RequiresPermissions("risk:point:savePointType")
    public ResultBean addPointType(@RequestBody RiskPointTypeBean bean) {
        RiskPointType type = riskPointService.addPointType(bean);
        return ResultBean.success(type);
    }

    @PostMapping("updatePointType")
    @ApiOperation("修改风险点类型")
    @RequiresPermissions(value = {"risk:point:savePointType", "risk:point:editPointType"}, logical = Logical.OR)
    public ResultBean updatePointType(@RequestBody RiskPointTypeBean bean) {
        RiskPointType type = riskPointService.updatePointType(bean);
        return ResultBean.success(type);
    }

    @GetMapping("editPointTypeOrderNumber")
    @ApiOperation("修改风险点类型序号")
    public ResultBean editPointTypeOrderNumber(Long upTypeId, Long downTypeId) {
        riskPointService.editPointTypeOrderNumber(upTypeId, downTypeId);
        return ResultBean.success("");
    }

    @GetMapping("findPointType")
    @ApiOperation("查看风险点类型")
    public ResultBean findPointType() {
        List<RiskPointTypeGroupBean> list = riskPointService.findPointType();
        return ResultBean.success(list);
    }

    @GetMapping("findTypeList")
    @ApiOperation("获取风险点类型列表")
    public ResultBean findTypeList(String typeCode) {
        List<RiskCodeAndNameBean> list = riskPointService.findTypeList(typeCode);
        return ResultBean.success(list);
    }

    @GetMapping("deletePointType")
    @ApiOperation("删除风险点类型")
    @RequiresPermissions("risk:point:deletePointType")
    public ResultBean deletePointType(Long typeId) {
        riskPointService.deletePointType(typeId);
        return ResultBean.success("");
    }

    @RequestMapping("add")
    @ApiOperation("添加")
    public Object add(@Valid RiskPoint entity, String subType,
                      @Valid @NotNull(field = "风险分区") Long riskDistrictId) throws Exception {
        if ((entity.getShared() == null || entity.getShared() == 0) && riskDistrictId == null) {
            // 非共享模式必选
            return ResultBean.fail(105, "风险分区 必选");
        }
        entity.setSubType(subType);
        if (riskDistrictId != null) {
            RiskDistrict district = riskDistrctService.findById(riskDistrictId);
            entity.setRiskDistrict(district);
        }
        if (entity.getShared() == null || entity.getShared() == 0) {
            entity.setStatus(RiskPointStatus.WAIT_COMMIT.getIndex());
        }
        RiskPoint save = riskPointService.add(entity);
        RiskPointBean bean = new RiskPointBean();
        BeanUtils.copyProperties(save, bean);
        if (save.getType() != null) {
            RiskPointType type = riskPointTypeDao.findByCode(save.getType());
            if (type != null) {
                bean.setTypeName(type.getName());
            }
        }
        if (save.getSubType() != null) {
            RiskPointType sType = riskPointTypeDao.findByCode(save.getSubType());
            if (sType != null) {
                bean.setSubTypeName(sType.getName());
            }
        }
        return ResultBean.success(bean);
    }

    @RequestMapping("addInManage")
    @ApiOperation("添加风险点在管理界面")
    @DynamicWriteData(bizType = "riskPointManage")
    public ResultBean addInManage(@RequestBody @Valid RiskPointVo riskPointVo) {
        try {
            return ResultBean.success(riskPointService.addRiskPoint(riskPointVo));
        } catch (ApiCoreException ae) {
            log.error("添加风险点在管理界面", ae);
            return ResultBean.fail(ae.getCode(), ae.getMessage());
        }
    }

    @RequestMapping("update")
    public Object update(@Valid RiskPoint entity, String subType,
                         @Valid @NotNull(field = "风险分区") Long riskDistrictId)
            throws Exception {
        if (entity.getId() == null) {
            return ResultBean.fail(102, "未指定主键");
        }
        //子类型
        entity.setSubType(subType);
        return ResultBean.success(riskPointService.update(entity, riskDistrictId));
    }

    @RequestMapping("updateInManage")
    @ApiOperation("修改风险点信息在管理界面")
    @DynamicWriteData(bizType = "riskPointManage", selector = "update")
    public Object updateInManage(@RequestBody RiskPointVo riskPointVo) {
        return riskPointService.updateRiskPoint(riskPointVo);
    }

    @GetMapping("submitAudit")
    @ApiOperation("风险点-提交审核")
    @RequiresPermissions(value = {"risk:assess:manage:submit", "risk:point:submitAudit"}, logical = Logical.OR)
    public ResultBean submitAudit(Long id) {
        return riskPointService.submitAudit(id);
    }

    @GetMapping("audit")
    @ApiOperation("风险点-审核")
    @RequiresPermissions("risk:point:audit")
    public ResultBean audit(RiskPointAuditBean bean) {
        return riskPointService.audit(bean);
    }

    @RequestMapping("updateDistrict")
    public ResultBean updateDistrict(Long[] riskDistrictIds) {
        for (Long riskDistrictId : riskDistrictIds) {
            riskDistrctService.updateDistrictRiskLevel(riskDistrictId);
        }
        return ResultBean.defaultSuccessResult();
    }

    @RequestMapping("page")
    @ApiOperation("风险点-分页查询")
    public Object page(Pageable page, Search condition) {
        try {
            page = PageDataUtils.addOrderByDesc(page, "id");
            condition.setBizId(1L);
            Page<RiskPointListBean> data = riskPointService.findByPage(page, condition);
            return ResultBean.pageData(data.getContent(), data.getTotalElements());
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    @GetMapping("findStatus")
    @ApiOperation("风险点-审核状态集合")
    public ResultBean findStatus(){
        List<JSONObject> list=new ArrayList<>();
        RiskPointStatus[] values = RiskPointStatus.values();
        for (RiskPointStatus value : values) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("key",value.getIndex());
            jsonObject.put("value",value.getStatus());
            list.add(jsonObject);
        }
        return ResultBean.success(list);
    }

    @GetMapping("findById")
    @ApiOperation("查看风险点")
    public ResultBean findById(Long riskPointId) {
        String name = "";
        RiskPoint point = riskPointService.findById(riskPointId);
        if (point != null) {
            name = point.getName();
        }
        return ResultBean.success(name);
    }

    @GetMapping("getById")
    @ApiOperation("查看风险点")
    public ResultBean getById(Long riskPointId) {
        RiskPointShowBean bean = riskPointService.getById(riskPointId);
        return ResultBean.success(bean);
    }

    @RequestMapping("shared-page")
    @ApiOperation("风险点库-分页查询")
    public Object sharedPage(Pageable page, Search condition) {
        try {
            page = PageDataUtils.addOrderByDesc(page, "id");

            Page<RiskPointListBean> data = riskPointService.findSharedByPage(page, condition);
            return ResultBean.pageData(data.getContent(), data.getTotalElements());
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    // 危险因素排查清单
    @RequestMapping("risk-factor-list")
    public Object getRiskFactorList(Pageable page, Long riskDistrictId) {
        try {
            page = PageDataUtils.addOrderByDesc(page, "riskDistrictId");
            Page<RiskPointListBean> data = riskPointService.findByPage(page, riskDistrictId);
            return ResultBean.pageData(data.getContent(), data.getTotalElements());
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    // 删除风险点
    @RequestMapping("delete")
    @ApiOperation("删除风险点")
    @RequiresPermissions(value = {"risk:point:delete", "risk:assess:manage:delete"}, logical = Logical.OR)
    public Object delete(Long id) {
        try {
            riskPointService.delete(id);
            return ResultBean.success("");
        } catch (ApiBusinessException e) {
            if (e.getCode() == Status.DELETE_CHECK_FAILED.getCode() && StringUtils.isNotEmpty(e.getMessage())) {
                List<RiskPointDeleteCheckVO> list = Lists.newArrayList();
                RiskPointDeleteCheckVO vo = JSONObject.parseObject(e.getMessage(), RiskPointDeleteCheckVO.class);
                list.add(vo);
                return ResultBean.fail(e.getCode(), "", list);
            } else {
                return ResultBean.fail(101, e.getMessage());
            }
        } catch (Exception e) {
            logger.error("删除失败", e);
            return ResultBean.fail(101, e.getMessage());
        }
    }

    // 批量删除风险点
    @RequestMapping("deletePoints")
    @ApiOperation("删除风险点")
    @RequiresPermissions(value = {"risk:point:delete", "risk:assess:manage:delete"}, logical = Logical.OR)
    public Object deletePoints(List<Long> ids) {
        riskPointService.deletePoints(ids);
        return ResultBean.success("");
    }

    @RequestMapping("set-control-level")
    public Object setControl(@Valid RiskPointControlLevelBean controlLevelBean) {
        try {
            // riskPointService.delete(id);
            riskPointService.setControlLevel(controlLevelBean);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("删除失败", e);
            return ResultBean.fail(101, "删除失败");
        }
    }

    @RequestMapping("control-level-page")
    public Object findControlLevelPage(Pageable page, RiskLevelListSearchBean searchBean) {
        try {
            // riskPointService.delete(id);
            page = PageDataUtils.addOrderByDesc(page, "code");
            Page<RiskLevelListBean> data = riskPointService.findRiskLevelControlPage(page, searchBean, 0);
            return ResultBean.pageData(data.getContent(), data.getTotalElements());
        } catch (Exception e) {
            logger.error("查询失败", e);
            return ResultBean.fail(101, "查询出异常");
        }
    }

    // 区域中的风险点列表详情
    @RequestMapping("list-in-district")
    public Object findRiskPointsInDistrict(Pageable page, @Valid @NotNull(field = "风险区域") Long riskDistrictId,
                                           String type) {
        try {
            // riskPointService.delete(id);
            RiskPointControlRiskListSearchBean c = new RiskPointControlRiskListSearchBean();
            c.setRiskDistrictId(riskDistrictId);
            c.setType(type);
            Page<RiskPointInDistrictListBean> data = riskPointService.findRiskPointsInDistrictPage(page, c);
            return ResultBean.pageData(data.getContent(), data.getTotalElements());
        } catch (Exception e) {
            logger.error("删除失败", e);
            return ResultBean.fail(101, "删除失败");
        }
    }

    @RequestMapping("findAll")
    public Object findAll(Long riskDistrictId) {
        return ResultBean.success(riskPointService.findAll(riskDistrictId));
    }

    @GetMapping("findList")
    @ApiOperation("查询所有风险单元")
    public Object findList() {
        return ResultBean.success(riskPointService.findList());
    }

    // 风险分区-控制风险评估-列表页
    @RequestMapping("control-risk-list")
    public Object findControlRiskList(Pageable page, RiskPointControlRiskListSearchBean condition) {
        try {
            page = PageDataUtils.addOrderByDesc(page, "code");
            // riskPointService.delete(id);
            Page<RiskPointInDistrictListBean> data = riskPointService.findRiskPointsInDistrictPage(page, condition);
            return ResultBean.pageData(data.getContent(), data.getTotalElements());
        } catch (Exception e) {
            logger.error("删除失败", e);
            return ResultBean.fail(101, "删除失败");
        }
    }

    // 风险分区-控制风险评估-scl评估提交
    @RequestMapping("do-scl-evaluation")
    public Object doSclEvaluation(@RequestBody @Valid RiskSclEvaluationBean bean) {
        try {
            // riskPointService.delete(id);
            RiskEvaluationRepo scl = riskPointService.doSclEvaluation(bean);
            Map<String, Object> result = new HashMap<>();
            result.put("id", scl.getId());
            result.put("riskLevelName", RiskLevels.findRiskLevelName(scl.getRiskLevel()));
            return ResultBean.success("评估成功");
        } catch (Exception e) {
            logger.error("评估失败", e);
            return ResultBean.fail(101, "评估失败");
        }
    }

    // 风险分区-风险点库-添加scl模板
    @RequestMapping("add-scl-template")
    public Object addSclTemplate(@RequestBody @Valid RiskSclEvaluationBean bean) {
        try {
            bean.setTemplate(true);
            RiskEvaluationRepo scl = riskPointService.doSclEvaluation(bean);
            Map<String, Object> result = new HashMap<>();
            result.put("id", scl.getId());
            result.put("riskLevelName", RiskLevels.findRiskLevelName(scl.getRiskLevel()));
            return ResultBean.success("评估成功");
        } catch (Exception e) {
            logger.error("评估失败", e);
            return ResultBean.fail(101, "评估失败");
        }
    }

    // 风险分区-控制风险评估-scl评估提交
    @RequestMapping("do-scl-evaluation-new")
    public Object doSclEvaluationNew(@RequestBody @Valid RiskSclEvaluationNewBean bean) {
        try {
            // riskPointService.delete(id);
            if (bean.getRiskPointId() == null && bean.getRiskDistrictId() == null) {
                return ResultBean.fail(400, "风险点和风险区域不能同时为空");
            }
            if (bean.getRiskPointId() == null && StringUtils.isBlank(bean.getRiskPointName())) {
                return ResultBean.fail(400, "必须选择风险点或者风险点名称");
            }
            RiskEvaluationRepo scl = riskPointService.doSclEvaluationNew(bean);
            Map<String, Object> result = new HashMap<>();
            result.put("id", scl.getId());
            result.put("riskLevelName", RiskLevels.findRiskLevelName(scl.getRiskLevel()));
            return ResultBean.success("评估成功");
        } catch (Exception e) {
            logger.error("评估失败", e);
            return ResultBean.fail(101, "评估失败");
        }
    }

    // 风险分区-控制风险评估-jha评估提交
    @RequestMapping("do-jha-evaluation")
    @PostMapping
    public Object doJhaEvaluation(@RequestBody @Valid RiskJhaEvaluationBean bean) {
        try {
            // riskPointService.delete(id);
            RiskEvaluationRepo jha = riskPointService.doJhaEvaluation(bean);
            Map<String, Object> result = new HashMap<>();
            result.put("id", jha.getId());
            result.put("riskLevel", jha.getRiskLevel());
            result.put("riskLevelName", RiskLevels.findRiskLevelName(jha.getRiskLevel()));
            return ResultBean.success(result);
        } catch (Exception e) {
            logger.error("评估失败", e);
            return ResultBean.fail(101, "评估失败");
        }
    }

    // 风险分区-风险点库-添加jha模板
    @RequestMapping("add-jha-template")
    @PostMapping
    public Object addJhaTemplate(@RequestBody @Valid RiskJhaEvaluationBean bean) {
        try {
            // 添加模板
            bean.setTemplate(true);
            RiskEvaluationRepo jha = riskPointService.doJhaEvaluation(bean);
            Map<String, Object> result = new HashMap<>();
            result.put("id", jha.getId());
            result.put("riskLevel", jha.getRiskLevel());
            result.put("riskLevelName", RiskLevels.findRiskLevelName(jha.getRiskLevel()));
            return ResultBean.success(result);
        } catch (Exception e) {
            logger.error("评估失败", e);
            return ResultBean.fail(101, "评估失败");
        }
    }

    // 风险分区-控制风险评估-jha评估提交
    @RequestMapping("do-jha-evaluation-new")
    @PostMapping
    public Object doJhaEvaluation(@RequestBody @Valid RiskJhaEvaluationNewBean bean) {
        try {
            // riskPointService.delete(id);
            if (bean.getRiskPointId() == null && bean.getRiskDistrictId() == null) {
                return ResultBean.fail(400, "风险点和风险区域不能同时为空");
            }
            if (bean.getId() == null && bean.getRiskPointId() == null && StringUtils.isBlank(bean.getRiskPointName())) {
                return ResultBean.fail(400, "必须选择风险点或者风险点名称");
            }
            if (bean.getRiskPointId() == null && bean.getId() != null) {
                // 兼容使用老模板调用新接口，只有id没有riskPointId的情况
                bean.setRiskPointId(bean.getId());
            }
            RiskEvaluationRepo jha = riskPointService.doJhaEvaluation(bean);
            Map<String, Object> result = new HashMap<>();
            result.put("id", jha.getId());
            result.put("evaluationId", jha.getEvaluationId());
            result.put("riskPointId", jha.getRiskPoint().getId());
            result.put("riskLevel", jha.getRiskLevel());
            result.put("riskLevelName", RiskLevels.findRiskLevelName(jha.getRiskLevel()));
            return ResultBean.success(result);
        } catch (Exception e) {
            logger.error("评估失败", e);
            return ResultBean.fail(101, "评估失败");
        }
    }

    // 风险分区-控制风险评估-评估明细
    @RequestMapping("evaluation-detail")
    public Object queryEvaluationDetail(@Valid @NotNull(field = "ID") Long id) {
        try {
            // riskPointService.delete(id);
            RiskPointEvaluationDetailBean bean = riskPointService.queryEvaluationDetail(id);
            return ResultBean.success(bean);
        } catch (Exception e) {
            logger.error("评估失败", e);
            return ResultBean.fail(101, "评估失败");
        }
    }

    // 获取上一次填写的模板
    @RequestMapping("evaluation-template")
    public Object queryEvaluationTemplate(Long id, String type) {
        try {
            // riskPointService.delete(id);
            RiskPointEvaluationBean template = riskPointService.queryEvaluationTemplate(id, type, false);
            return ResultBean.success(template);
        } catch (Exception e) {
            logger.error("评估失败", e);
            return ResultBean.fail(101, "评估失败");
        }
    }

    // 风险分区-评估详情-删除
    @RequestMapping("delete-evaluation")
    public Object deleteEvaluation(@Valid @NotNull(field = "ID") Long id, @Valid @NotNull String type) {
        try {
            // riskPointService.delete(id);
            riskPointService.deleteEvaluation(id, type);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("删除失败", e);
            return ResultBean.fail(101, "删除失败");
        }
    }

    // 风险分区-两单三卡-安全风险分级管控清单
    @RequestMapping("safety-control-list")
    public Object getSafetyControlList(Pageable page, RiskPointSafetyControlListSearchBean condition) {
        try {
            // riskPointService.delete(id);
            page = PageDataUtils.addOrderByDesc(page, "code");
            Page<RiskPointEvaluationDetailBean> pageData = riskPointService.findSafetyControlListPage(page, condition);
            return ResultBean.pageData(pageData);
        } catch (Exception e) {
            logger.error("评估失败", e);
            return ResultBean.fail(101, "评估失败");
        }
    }

    // 风险点风险评估记录
    @RequestMapping("risk-point-evaluation-history")
    public Object getRiskPointEvaluationHistory(Pageable page, Long id,
                                                RiskPointSafetyControlListSearchBean condition) {
        try {
            // riskPointService.delete(id);
            // page = PageDataUtils.addOrderByDesc(page, "createTime");
            Page<RiskPointEvaluationBean> pageData = riskPointService.findRiskPointEvaluationHistory(page, id,
                    condition);
            return ResultBean.pageData(pageData);
        } catch (Exception e) {
            logger.error("查询评估历史失败", e);
            return ResultBean.fail(101, "查询评估历史失败:" + e.getMessage());
        }
    }

    // 获取共享风险点集合
    // type: job 作业证; device 设备设施
    @RequestMapping("shared-simple-list")
    public Object getSharedSimpleList(String type) {
        try {
            List<RiskPointInDistrictListBean> data = riskPointService.findSharedSimpleList(type);
            return ResultBean.success(data);
        } catch (Exception e) {
            logger.error("查询评估历史失败", e);
            return ResultBean.fail(101, "查询评估历史失败:" + e.getMessage());
        }
    }

    /**
     * 风险点评估pdf打印
     */
    @RequestMapping("pointPdfPrint")
    @RequiresPermissions("risk:point:pointPdfPrint")
    @ApiOperation(value = "风险点库评估PDF打印")
    public void pointPdfPrint(Long id, HttpServletResponse response) {
        response.setContentType("application/pdf;charset=UTF-8");
        Map<String, Object> dataMap = riskPointService.pointPdfPrint(id);
        File file = null;
        try {
            file = printExportUtil.generatePDF(dataMap, "workSafetyCertRiskEvalTemp");
            response.setContentType("application/pdf;charset=UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        fileToStreamResult(file, "pdf下载失败", response);
    }

    private void fileToStreamResult(File file, String message, HttpServletResponse response) {
        try {
            if (file.exists()) {
                byte[] cache = new byte[2048];
                int len = 0;
                FileInputStream fis = new FileInputStream(file);
                while ((len = fis.read(cache)) != -1) {
                    response.getOutputStream().write(cache, 0, len);
                }
                fis.close();
                response.getOutputStream().flush();
            }
        } catch (IOException e) {
            log.error(message, e);
        }
    }
}
